
#if defined(WIN32) || defined(WIN64)
#pragma unmanaged
#endif

#include <Liberty3D/Library/AssetDepotFolder.h>
#include <Liberty3D/Engine/ISerializer.h>

#include <algorithm>

using namespace Liberty::Engine;
using namespace Liberty::Library;

AssetDepotEntry::AssetDepotEntry() : hashMeta(0), revisionMeta(1) {
}

AssetDepotEntry::~AssetDepotEntry() {
}

std::string AssetDepotEntry::projectPath() const {
    std::string                      s(name);
    std::shared_ptr<AssetDepotEntry> c(parent.lock());
    
    while (c) {
        if (c->name.length() == 0) {
            break;
        }
        
        s = c->name + "/" + s;
        c = c->parent.lock();
    }
    
    return s;
}

void AssetDepotEntry::serializeObject(ISerializer* s) {
    s->serialize("uuid",           uuid);
    s->serialize("parent",         parent);
    s->serialize("name",           name);
    s->serialize("hashMeta",       hashMeta);
    s->serialize("revisionMeta",   revisionMeta);
}

void AssetDepotEntry::serializeEnd(ISerializer* s) {
}

AssetDepotEntryFile::AssetDepotEntryFile() : revision(1), hash(0) {
}

const char* AssetDepotEntryFile::serializeClassName() const {
    return "file";
}

void AssetDepotEntryFile::serializeObject(Liberty::Engine::ISerializer* s) {
    AssetDepotEntry::serializeObject(s);

    s->serialize("revision", revision);
    s->serialize("hash",     hash);
}

AssetDepotEntryFolder::AssetDepotEntryFolder() {
}

const char* AssetDepotEntryFolder::serializeClassName() const {
    return "folder";
}

void AssetDepotEntryFolder::serializeObject(Liberty::Engine::ISerializer* s) {
    AssetDepotEntry::serializeObject(s);
    
    Serializer<EntryList>()(s, "childs", childs);
}

std::shared_ptr<AssetDepotEntry> AssetDepotEntryFolder::find(const std::string& n) const {
    EntryList::const_iterator it, end(childs.end());
    
    for (it = childs.begin(); it != end; ++it) {
        const std::shared_ptr<AssetDepotEntry>& ref(*it);
        
        if (ref->name == n) {
            return ref;
        }
    }
    
    return std::shared_ptr<AssetDepotEntry>();
}

std::list<std::string> AssetDepotEntryFolder::names() const {
    std::list<std::string> n;
    
    EntryList::const_iterator it, end(childs.end());
    
    for (it = childs.begin(); it != end; ++it) {
        n.push_back((*it)->name);
    }
    
    return n;
}

void AssetDepotEntryFolder::add(const std::shared_ptr<AssetDepotEntry>& e) {
    childs.push_back(e);
}

void AssetDepotEntryFolder::remove(const std::shared_ptr<AssetDepotEntry>& e) {
    EntryList::iterator it(std::find(childs.begin(), childs.end(), e));

    if (it != childs.end()) {
        childs.erase(it);
    }
}
